#include "sql.h"
#include "sqlite.h"
#include <types.h>
#include <klibc/stdio.h>
#include <klibc/malloc.h>
#include <mm.h>


struct sqlite3_vfs sql_vfs =
{
	.zName = "spvfs",
	.mxPathname = 512
	
	//pAppData;          /* Pointer to application-specific data */
  //int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
               int flags, int *pOutFlags);
  /*int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  void (*xDlClose)(sqlite3_vfs*, void*);
  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  int (*xSleep)(sqlite3_vfs*, int microseconds);
  int (*xCurrentTime)(sqlite3_vfs*, double*);
  int (*xGetLastError)(sqlite3_vfs*, int, char *);
  */
};

/*
static int sql_callback(void *NotUsed, int argc, char **argv, char **azColName){
  int i;
  for(i=0; i<argc; i++){
    printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
  }
  printf("\n");
  return 0;
}*/

/**
 * Inizializza sql, ed esegue una simpatica interfaccia per le 
 * interrogazioni da tastiera
 */
int sql_main(int argc, char **argv)
{
	sqlite3_initialize();
	
	sqlite3 *db;
	char *err = 0;
	int rc;
	char buf[1024];

	rc = sqlite3_open("/tmp/db_test.db", &db);
	if(rc)
	{
		printf("can't open database: %s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		return 1;
	}
	
	while(1)
	{
		printf("sql> ");
		scanf("%s", buf);
		
		if(strcmp(buf, "exit") == 0) break;
		
		rc = sqlite3_exec(db, buf, NULL, 0, &err); //callback, 0, &err);
		
		if(rc != SQLITE_OK)
		{
			printf("sql error: %s\n", err);
			sqlite3_free(err);
		}
	}
	
	sqlite3_close(db);
	
	sqlite3_shutdown();
	return 0;	
}


/**
 * 
 */
int sqlite3_os_init()
{
	sqlite3_config(SQLITE_CONFIG_MALLOC, malloc, free, realloc, mm_get_usable_size);
	sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
	sqlite3_vfs_register(&sql_vfs, 1);
}



/**
 * 
 */
int sqlite3_os_end()
{
	
}
